<?php

namespace app\admin\controller\classes;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 
 *
 * @icon fa fa-file
 */
class Classes extends Backend
{

    /**
     * Classes模型对象
     */
    protected $model = null;
    protected $shopid = null;
    protected $noNeedRight = ["lists", "status", 'lists2', 'classes_type', 'changestatus'];
    protected $noNeedLogin = ["lists", "status", 'lists2', 'classes_type', 'changestatus'];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid = false;
        // 根据URL参数 classes_type 动态选择模型：1=学校班级(Classes)，2=社区教学点班级(OcationClass)
        // 同时将 classes_type 映射到现有逻辑使用的 rel_type，保持兼容
        $classesTypeParam = null;
        try {
            // 优先从GET中读取，其次从通用参数中读取
            $classesTypeParam = $this->request->get('classes_type');
            if ($classesTypeParam === null || $classesTypeParam === '') {
                $classesTypeParam = $this->request->param('classes_type');
            }
        } catch (\Exception $e) {
            $classesTypeParam = null;
        }

        // 标准化为整数 1/2
        $classesType = ($classesTypeParam !== null && $classesTypeParam !== '') ? intval($classesTypeParam) : null;

        // 如果未显式传递 classes_type，则保持原有默认模型
        if ($classesType === 2) {
            $this->model = model('OcationClass');
            // 将 classes_type 映射为现有代码广泛使用的 rel_type
            if (!isset($_REQUEST['rel_type'])) {
                $_REQUEST['rel_type'] = 2;
            }
        } else {
            // 默认为学校班级模型
            $this->model = model('Classes');
            if ($classesType === 1 && !isset($_REQUEST['rel_type'])) {
                $_REQUEST['rel_type'] = 1;
            }
        }
        // 传递到前端，便于JS按需处理
        $this->assignconfig('classes_type', $_REQUEST['classes_type'] ?? $classesType ?? 1);
        $this->modelValidate = true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                try {
                    return $this->selectpage();
                } catch (\Exception $e) {
                    // 如果selectpage出错，返回空结果
                    return json(['list' => [], 'total' => 0]);
                }
            }

            // 处理快捷搜索请求
            if ($this->request->get('search') !== null && $this->request->get('search') !== "") {
                return $this->quickSearch();
            }
            list($where, $sort, $order, $offset, $limit, $page, $alias, $bind) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");

            // 调试日志
            error_log("Classes Index - city_id: $city_id, school_id: $school_id");

            // 构建总数查询
            $is_ocation_class_for_total = (isset($_REQUEST['rel_type']) && intval($_REQUEST['rel_type']) == 2);

            if ($is_ocation_class_for_total) {
                // 当rel_type=2时，从社区班级表fa_ocation_class获取总数
                $total = Db::name('ocation_class')->alias('oc')
                    ->join("fa_course_table_autoplan_temp t", "t.ocation_class_id=oc.id", "LEFT")
                    ->where("oc.status", "=", 1);

                // 每个ocation_id仅保留最小的oc.id记录
                $minIdSubSql_total = Db::name('ocation_class')->alias('oc2')
                    ->where('oc2.status', 1)
                    ->field('MIN(oc2.id) AS min_id, oc2.ocation_id')
                    ->group('oc2.ocation_id')
                    ->buildSql();
                $total = $total->join([$minIdSubSql_total => 'oc_min'], 'oc_min.ocation_id = oc.ocation_id AND oc.id = oc_min.min_id', 'INNER');

                // 社区管理员权限控制：只能看到指定教学点的班级
                if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8) {
                    // 社区管理员：只能看到该教学点同级的班级和该教学点所有子教学点的班级
                    $allowedOcationIds = model("Ocation")::getChildOcationIds($_SESSION['think']['admin']['ocation_id'], true);
                    if (!empty($allowedOcationIds)) {
                        $total = $total->where("oc.ocation_id", "in", $allowedOcationIds);
                    } else {
                        // 如果没有可访问的教学点，返回空结果
                        $total = $total->where("1", "=", "0");
                    }
                } else {
                    // 添加城市和学校过滤（非社区管理员）
                    if (!empty($city_id)) {
                        $total = $total->where("t.city_id", "=", $city_id);
                    } else if (!empty($school_id)) {
                        $total = $total->where("t.school_id", "=", $school_id);
                    } else if (isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
                        // 通过教学点关联学校
                        $total = $total->where("t.school_id", "=", $_SESSION['think']['admin']['school_id']);
                    }
                }

                if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                    $total = $total->where("oc.name", "like", "%" . $_REQUEST['search'] . "%");
                }
            } else {
                // 其他类型使用原来的逻辑
                $total = $this->model->alias('c')
                    ->join("fa_course_table_autoplan_temp t", "t.classes_id=c.id", "LEFT")
                    ->where("c.status", "=", 1);

                // 添加城市和学校过滤
                if (!empty($city_id)) {
                    $total = $total->where("c.city_id", "=", $city_id);
                } else if (!empty($school_id)) {
                    $total = $total->where("c.school_id", "=", $school_id);
                } else if (isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
                    $total = $total->where("c.school_id", "=", $_SESSION['think']['admin']['school_id']);
                }

                if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                    $total = $total->where("c.name", "like", "%" . $_REQUEST['search'] . "%");
                }

                if (isset($_REQUEST['rel_type'])) {
                    $total = $total->where("c.classes_type", intval($_REQUEST['rel_type']));
                }
            }

            // 根据class_status参数筛选总数
            if (isset($_REQUEST['class_status']) && $_REQUEST['class_status'] !== 'all') {
                $today = date('Y-m-d');
                if ($_REQUEST['class_status'] === '1' || $_REQUEST['class_status'] === 1) {
                    // 正在进行中：已排课且最大日期大于等于当前日期
                    if ($is_ocation_class_for_total) {
                        $total = $total->group("oc.id")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '$today')");
                    } else {
                        $total = $total->group("c.id")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '$today')");
                    }
                } elseif ($_REQUEST['class_status'] === '0' || $_REQUEST['class_status'] === 0) {
                    // 已经结束：已排课且最大日期小于当前日期
                    if ($is_ocation_class_for_total) {
                        $total = $total->group("oc.id")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '$today')");
                    } else {
                        $total = $total->group("c.id")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '$today')");
                    }
                } elseif ($_REQUEST['class_status'] === 'unscheduled') {
                    // 未排课的班级：没有任何排课记录
                    if ($is_ocation_class_for_total) {
                        $total = $total->group("oc.id")
                            ->having("MAX(t.date) IS NULL");
                    } else {
                        $total = $total->group("c.id")
                            ->having("MAX(t.date) IS NULL");
                    }
                }
            }

            // 如果是社区班级且未指定状态筛选，也需要按ocation_id去重
            if ($is_ocation_class_for_total && (!isset($_REQUEST['class_status']) || $_REQUEST['class_status'] === 'all')) {
                $total = $total->group('oc.ocation_id');
            } else {
                $total = $total->count();
                //Db::name('ocation_class')->getlastsql()
                $this->assign('total', $total);
            }

            // 构建列表查询 学校 社区都经过
            $list = $this->model->alias('c')
                ->join("fa_course_table_autoplan_temp t", "t.classes_id=c.id", "LEFT")
                ->join("fa_class_sequence s", "s.class_id=c.id", "LEFT") // 关联班级序号表
                ->where("c.status", "=", 1);

            // 添加城市和学校过滤
            if (!empty($city_id)) {
                $list = $list->where("c.city_id", "=", $city_id);
            } else if (!empty($school_id)) {
                $list = $list->where("c.school_id", "=", $school_id);
            } else if (isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
                $list = $list->where("t.school_id", "=", $_SESSION['think']['admin']['school_id']);
            }

            if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                $list = $list->where("c.name", "like", "%" . $_REQUEST['search'] . "%");
            }

            if (isset($_REQUEST['rel_type'])) {
                $rel_type = intval($_REQUEST['rel_type']);
                if ($rel_type == 2) {
                    // 当rel_type=2时，从社区班级表fa_ocation_class获取数据
                    // 重新构建查询，使用fa_ocation_class作为主表
                    $list = Db::name('ocation_class')->alias('oc')
                        ->join("fa_course_table_autoplan t", "t.ocation_class_id=oc.id", "LEFT")
                        ->where("oc.status", "=", 1);

                    // 每个ocation_id仅保留最小的oc.id记录
                    $minIdSubSql_list = Db::name('ocation_class')->alias('oc2')
                        ->where('oc2.status', 1)
                        ->field('MIN(oc2.id) AS min_id, oc2.ocation_id')
                        ->group('oc2.ocation_id')
                        ->buildSql();
                    $list = $list->join([$minIdSubSql_list => 'oc_min'], 'oc_min.ocation_id = oc.ocation_id AND oc.id = oc_min.min_id', 'LEFT');

                    // 应用搜索条件
                    if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                        $list = $list->where("oc.name", "like", "%" . $_REQUEST['search'] . "%");
                    }

                    // 社区管理员权限控制：只能看到指定教学点的班级
                    if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8) {
                        // 社区管理员：只能看到该教学点同级的班级和该教学点所有子教学点的班级
                        $allowedOcationIds = model("Ocation")::getChildOcationIds($_SESSION['think']['admin']['ocation_id'], true);
                        if (!empty($allowedOcationIds)) {
                            $list = $list->where("oc.ocation_id", "in", $allowedOcationIds);
                        } else {
                            // 如果没有可访问的教学点，返回空结果
                            $list = $list->where("1", "=", "0");
                        }
                    } else {
                        // 添加城市和学校过滤（非社区管理员）
                        if (!empty($city_id)) {
                            $list = $list->where("t.city_id", "=", $city_id);
                        } else if (!empty($school_id)) {
                            $list = $list->where("t.school_id", "=", $school_id);
                        } else if (isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
                            // 通过教学点关联学校
                            $list = $list->where("t.school_id", "=", $_SESSION['think']['admin']['school_id']);
                        }
                    }
                } else {
                    // 其他类型仍然使用原来的逻辑  学校专用
                    //$list =$list->join("fa_class_sequence s", "s.class_id=c.id", "LEFT");
                    $list = $list->where("c.classes_type", $rel_type);
                }
            }

            // 根据class_status参数筛选列表
            $is_ocation_class = (isset($_REQUEST['rel_type']) && intval($_REQUEST['rel_type']) == 2);

            if (isset($_REQUEST['class_status']) && $_REQUEST['class_status'] !== 'all') {
                $today = date('Y-m-d');
                if ($_REQUEST['class_status'] === '1' || $_REQUEST['class_status'] === 1) {
                    // 正在进行中：已排课且最大日期大于等于当前日期
                    if ($is_ocation_class) {
                        $list = $list->group("oc.id")
                            ->field("oc.id,oc.community_id,oc.ocation_id,oc.cover, oc.name, oc.id as class_id, oc.ocation_id, t.city_id, t.school_id, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, oc.id as sequence_number, 'ocation_class' as sequence_type, 2 as classes_type")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '$today')");
                    } else {
                        $list = $list->group("c.id")
                            ->field("c.*, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, t.city_id, t.school_id, s.sequence_number, s.class_type as sequence_type")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '$today')");
                    }
                } elseif ($_REQUEST['class_status'] === '0' || $_REQUEST['class_status'] === 0) {
                    // 已经结束：已排课且最大日期小于当前日期
                    if ($is_ocation_class) {
                        $list = $list->group("oc.id")
                            ->field("oc.id,oc.community_id,oc.ocation_id,oc.cover, oc.name, oc.id as class_id, oc.ocation_id, t.city_id, t.school_id, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, oc.id as sequence_number, 'ocation_class' as sequence_type, 2 as classes_type")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '$today')");
                    } else {
                        $list = $list->group("c.id")
                            ->field("c.*, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, t.city_id, t.school_id, s.sequence_number, s.class_type as sequence_type")
                            ->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '$today')");
                    }
                } elseif ($_REQUEST['class_status'] === 'unscheduled') {
                    // 未排课的班级：没有任何排课记录
                    if ($is_ocation_class) {
                        $list = $list->group("oc.id")
                            ->field("oc.id,oc.community_id,oc.ocation_id,oc.cover, oc.name, oc.id as class_id, oc.ocation_id, t.city_id, t.school_id, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, oc.id as sequence_number, 'ocation_class' as sequence_type, 2 as classes_type")
                            ->having("MAX(t.date) IS NULL");
                    } else {
                        $list = $list->group("c.id")
                            ->field("c.*, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, t.city_id, t.school_id, s.sequence_number, s.class_type as sequence_type")
                            ->having("MAX(t.date) IS NULL");
                    }
                }
            } else {
                // 没有状态筛选时（全部班级），仍然需要分组获取日期信息
                if ($is_ocation_class) {
                    if ($_REQUEST['class_status'] == 'all') {
                        $list = $list->field("oc.id as id,oc.community_id,oc.ocation_id,oc.cover,oc.name, oc.id as class_id, oc.ocation_id, t.city_id, t.school_id, t.ocation_id, t.id t_id, oc.id as sequence_number, 'ocation_class' as sequence_type, 2 as classes_type");
                    } else {
                        $list = $list->field("oc.id,oc.community_id,oc.ocation_id,oc.cover,oc.name, oc.id as class_id, oc.ocation_id, t.city_id, t.school_id, t.ocation_id, t.id t_id, oc.id as sequence_number, 'ocation_class' as sequence_type, 2 as classes_type");
                    }
                } else {
                    $list = $list->group("c.id")
                        ->field("c.*, MIN(t.date) as start_date, MAX(t.date) as end_date, t.ocation_id, t.id t_id, s.sequence_number, s.class_type as sequence_type");
                }
            }

            // 处理排序
            if ($sort === 'sequence_number') {
                // 按序号排序
                if ($is_ocation_class) {
                    // 简单的解决方案：先过滤NULL值再排序 社区
                    if ($_REQUEST['class_status'] == 'all') {
                        $list = $list->where('oc.sequence_number', 'not null')
                            ->order("oc.sequence_number", $order)
                            ->group("oc.ocation_id")
                            ->limit($offset, $limit)
                            ->select();
                    } else {
                        $list = $list->where('oc.sequence_number', 'not null')
                            ->order("oc.sequence_number", $order)
                            ->group("oc.ocation_id")
                            ->limit($offset, $limit)
                            ->select();
                    }
                } else {
                    // 完全重新构建查询，避免任何状态污染
                    // 使用原生SQL构建查询，避免查询构建器状态问题
                    $school_id = intval($_SESSION['think']['admin']['school_id']);
                    $classes_type = intval($_REQUEST['rel_type']);
                    $today = date('Y-m-d');

                    // 构建基础SQL
                    $sql = "SELECT c.*, MIN(t.date) as start_date, MAX(t.date) as end_date,
                                   t.ocation_id, t.id as t_id, s.sequence_number, s.class_type as sequence_type,ct.ocourse_count
                            FROM eb_classes c
                            LEFT JOIN fa_course_table_autoplan_temp t ON t.classes_id = c.id
                            LEFT JOIN fa_class_sequence s ON s.class_id = c.id
                            LEFT JOIN (select id,classes_id,ocourse_count from fa_course_table_classplant where ocourse_count>0 group by classes_id) ct ON s.class_id = ct.classes_id
                            WHERE c.status = 1
                              AND c.school_id = {$school_id}
                              AND c.classes_type = {$classes_type}
                              ";

                    // 应用搜索条件
                    if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                        $search = addslashes(trim($_REQUEST['search']));
                        $sql .= " AND c.name LIKE '%{$search}%'";
                    }

                    // 添加分组
                    $sql .= " GROUP BY c.id";

                    // 应用状态筛选
                    if (isset($_REQUEST['class_status']) && $_REQUEST['class_status'] !== 'all') {
                        if ($_REQUEST['class_status'] === '1' || $_REQUEST['class_status'] === 1) {
                            // 正在进行中：已排课且最大日期大于等于当前日期
                            $sql .= " HAVING (MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '{$today}')";
                        } elseif ($_REQUEST['class_status'] === '0' || $_REQUEST['class_status'] === 0) {
                            // 已经结束：已排课且最大日期小于当前日期
                            $sql .= " HAVING (MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '{$today}')";
                        } elseif ($_REQUEST['class_status'] === 'unscheduled') {
                            // 未排课的班级：没有任何排课记录
                            $sql .= " HAVING MAX(t.date) IS NULL";
                        }
                    }

                    //实现计算$total - 使用原生SQL计算总数
                    $totalSql = "SELECT COUNT(DISTINCT c.id) as total
                                FROM eb_classes c
                                LEFT JOIN fa_course_table_autoplan_temp t ON t.classes_id = c.id
                                LEFT JOIN fa_class_sequence s ON s.class_id = c.id
                                WHERE c.status = 1
                                  AND c.school_id = {$school_id}
                                  AND c.classes_type = {$classes_type}
                                  ";

                    // 添加搜索条件（与主查询保持一致）
                    if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                        $search = addslashes(trim($_REQUEST['search']));
                        $totalSql .= " AND c.name LIKE '%{$search}%'";
                    }

                    // 添加状态筛选条件（与主查询保持一致）
                    if (isset($_REQUEST['class_status']) && $_REQUEST['class_status'] !== 'all') {
                        $totalSql .= " GROUP BY c.id";
                        if ($_REQUEST['class_status'] === '1' || $_REQUEST['class_status'] === 1) {
                            // 正在进行中：已排课且最大日期大于等于当前日期
                            $totalSql .= " HAVING (MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '{$today}')";
                        } elseif ($_REQUEST['class_status'] === '0' || $_REQUEST['class_status'] === 0) {
                            // 已经结束：已排课且最大日期小于当前日期
                            $totalSql .= " HAVING (MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '{$today}')";
                        } elseif ($_REQUEST['class_status'] === 'unscheduled') {
                            // 未排课的班级：没有任何排课记录
                            $totalSql .= " HAVING MAX(t.date) IS NULL";
                        }
                        // 当有HAVING条件时，需要用子查询来计算总数
                        $totalSql = "SELECT COUNT(*) as total FROM ({$totalSql}) as temp";
                    }

                    // 执行总数查询
                    $totalResult = Db::query($totalSql);
                    $total = isset($totalResult[0]['total']) ? intval($totalResult[0]['total']) : 0;


                    // 添加排序和分页
                    $sql .= " ORDER BY s.sequence_number {$order} LIMIT {$offset}, {$limit}";

                    // 执行原生SQL查询
                    $list = Db::query($sql);
                }
            } else {
                // 其他字段排序
                if ($is_ocation_class) {
                    // 对于社区班级表，需要调整字段名
                    $ocation_sort = $sort;
                    if ($sort == 'name') {
                        $ocation_sort = 'oc.name';
                    } elseif ($sort == 'id') {
                        $ocation_sort = 'oc.id';
                    } elseif (strpos($sort, 'c.') === 0) {
                        $ocation_sort = str_replace('c.', 'oc.', $sort);
                    }

                    // 对sequence_number字段使用特殊处理
                    if ($ocation_sort === 'oc.sequence_number') {
                        $list = $list->where('oc.sequence_number', 'not null')
                            ->order("oc.sequence_number", $order)
                            ->group("oc.ocation_id")
                            ->limit($offset, $limit)
                            ->select();
                    } else {
                        $list = $list->order($ocation_sort, $order)
                            ->group("oc.ocation_id")
                            ->limit($offset, $limit)
                            ->select();
                    }
                } else {
                    // 社区路径下（rel_type=2）其它字段排序也需要按ocation_id分组去重
                    if ($is_ocation_class) {
                        $list = $list->group('oc.ocation_id')
                            ->order($ocation_sort, $order)
                            ->limit($offset, $limit)
                            ->select();
                    } else {
                        $list = $list->order($sort, $order)
                            ->limit($offset, $limit)
                            ->select();
                    }
                }
            }

            // 将查询结果转换为数组
            $list = is_array($list) ? $list : ($list ? $list->toArray() : []);
            //echo $this->model->getlastsql();exit;
            for ($i = 0; $i < count($list); $i++) {
                if ($rel_type == 1) {
                    $list[$i]['city_id'] = model("Cityarea")->getCity_idTextAttr($list[$i]['city_id'], $list[$i]);
                    $list[$i]['school_id'] = model("School")->getSchool_idTextAttr($list[$i]['school_id'], $list[$i]);
                    $list[$i]['subject_lv'] = model("Subjectlv")->getSubject_lvTextAttr($list[$i]['subject_lv'], $list[$i]);
                    $list[$i]['show_in_team'] = $this->model->getShow_in_teamTextAttr($list[$i]['show_in_team'], $list[$i]);
                    $list[$i]['is_check'] = $this->model->getIs_checkTextAttr($list[$i]['is_check'], $list[$i]);
                    $list[$i]['allow_see'] = $this->model->getAllow_seeTextAttr($list[$i]['allow_see'], $list[$i]);
                    $list[$i]['class_type'] = $this->model->getClass_typeTextAttr($list[$i]['class_type'], $list[$i]);
                    $list[$i]['type'] = $this->model->getTypeTextAttr($list[$i]['type'], $list[$i]);
                    $list[$i]['leader_id'] = model("User")->getUser_idTextAttr($list[$i]['leader_id'], $list[$i]);
                    $list[$i]['manager_id'] = model("User")->getUser_idTextAttr($list[$i]['manager_id'], $list[$i]);
                    $list[$i]['is_apply_to_join'] = $this->model->getIs_apply_to_joinTextAttr($list[$i]['is_apply_to_join'], $list[$i]);
                    $list[$i]['creator_type'] = $this->model->getCreator_typeTextAttr($list[$i]['creator_type'], $list[$i]);
                    $list[$i]['province_id'] = $this->model->getProvice_idTextAttr($list[$i]['province_id'], $list[$i]);
                    $list[$i]['addresslv_id'] = model("Addresslv")->getAddresslv_idTextAttr($list[$i]['addresslv_id'], $list[$i]);
                    $list[$i]['rel_id'] = model("School")->getSchool_idTextAttr($list[$i]['rel_id'], $list[$i]);
                    $list[$i]['count_total'] = $list[$i]['ocourse_count'];
                    $list[$i]['community_id'] = model("Community")->getCommunity_idTextAttr($list[$i]['community_id'], $list[$i]);
                    $list[$i]['ocation_id'] = model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'], $list[$i]);
                    $list[$i]['apply_num'] = db::name("eb_apply_form_item")->where("classes_id", $list[$i]['id'])->where("status", 1)->count();
                    // 返回统计用的原始数据
                    $list[$i]['chart_data'] = [
                        'apply_num' => $list[$i]['apply_num'], // 实际报名人数
                        'max_num' => $list[$i]['num']     // 班级最大容量
                    ];
                } else {
                    $list[$i]['community_id'] = model("Community")->getCommunity_idTextAttr($list[$i]['community_id'], $list[$i]);
                    $list[$i]['ocation_id'] = model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'], $list[$i]);
                }
                // 处理班级序号
                if (!empty($list[$i]['sequence_number'])) {
                    // 格式化序号（带前缀）
                    $prefix = $list[$i]['sequence_type'] == 1 ? 'S-' : 'C-';
                    $list[$i]['formatted_sequence'] = $prefix . str_pad($list[$i]['sequence_number'], 3, '0', STR_PAD_LEFT);
                } else {
                    // 如果没有序号，尝试分配一个
                    $classType = $list[$i]['rel_type'];
                    $schoolId = $list[$i]['school_id'];
                    $communityId = $list[$i]['community_id'];
                    model('ClassSequence')->assignSequence($list[$i]['id'], $classType, $schoolId, $communityId);

                    // 重新获取序号
                    $sequence = model('ClassSequence')->where('class_id', $list[$i]['id'])->find();
                    if ($sequence) {
                        $prefix = $sequence['class_type'] == 1 ? 'S-' : 'C-';
                        $list[$i]['formatted_sequence'] = $prefix . str_pad($sequence['sequence_number'], 3, '0', STR_PAD_LEFT);
                        $list[$i]['sequence_number'] = $sequence['sequence_number'];
                    } else {
                        $list[$i]['formatted_sequence'] = '';
                        $list[$i]['sequence_number'] = '';
                    }
                }

                $list[$i]['cover'] = createImg($_SERVER["DOCUMENT_ROOT"] . "/" . $list[$i]["cover"], "220", "220");
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        //        $this->assignconfig("relType",$_REQUEST['relType']);
        //        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        // 将后端的 rel_type 传递给前端，便于 JS 使用：Config.rel_type
        $this->assignconfig("relType", isset($_REQUEST['rel_type']) ? intval($_REQUEST['rel_type']) : 1);
        return $this->view->fetch();
    }
    /**
     * 获取社区管理员可访问的教学点ID列表
     *
     * @return array 教学点ID数组
     */
    private function getCommunityManagerOcationIds()
    {
        $adminInfo = $_SESSION['think']['admin'];
        $ocationIds = [];

        // 如果管理员有关联的教学点ID
        if (isset($adminInfo['ocation_id']) && $adminInfo['ocation_id']) {
            $currentOcationId = $adminInfo['ocation_id'];

            // 添加当前教学点
            $ocationIds[] = $currentOcationId;

            // 获取同级教学点（相同父级的教学点）
            $currentOcation = Db::name('ocation')->where('id', $currentOcationId)->find();
            if ($currentOcation && $currentOcation['pid']) {
                $siblingIds = Db::name('ocation')
                    ->where('pid', $currentOcation['pid'])
                    ->where('status', 1)
                    ->column('id');
                $ocationIds = array_merge($ocationIds, $siblingIds);
            }

            // 获取所有子教学点，使用Ocation控制器的方法
            $ocationController = new \app\admin\controller\ocation\Ocation();
            $childIds = $ocationController->getChildOcationIds($currentOcationId);
            $ocationIds = array_merge($ocationIds, $childIds);
        }

        return array_unique($ocationIds);
    }


    /**
     * 添加
     */
    public function add()
    {
        $user=$this->auth->getUserInfo();
        $classes_type = $this->request->request("classes_type");
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }
                    //判断下拉菜单是否为空
                    if (isset($params['classes_type'])) {
                        if (empty($params['classes_type'])) {
                            $this->error('请选择班级类型');
                        }
                    }
                    if (isset($params['school_id'])) {
                        if (empty($params['school_id'])) {
                            $this->error('请选择学校');
                        }
                    }
                    if (isset($params['subject_lv'])) {
                        if (empty($params['subject_lv'])) {
                            $this->error('课程名称');
                        }
                    }
                    //名称查重
                    $where = [
                        'name' => $params['name'],
                        'status' => 1,
                    ];
                    if ($this->model->where($where)->find()) {
                        $this->error('名称重复');
                    }

                    // 自动插入session中的城市和学校ID
                    if (isset($_SESSION['think']['admin']['province_id']) && !empty($_SESSION['think']['admin']['province_id'])) {
                        $params['province_id'] = $_SESSION['think']['admin']['province_id'];
                    }
                    if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                    if (isset($_SESSION['think']['admin']['district_id']) && !empty($_SESSION['think']['admin']['district_id'])) {
                        $params['district_id'] = $_SESSION['think']['admin']['district_id'];
                    }
                    if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }

                    // 调试日志
                    error_log("Classes Add - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                    $datatime = date("Y-m-d H:i:s");
                    $params['create_time'] = $datatime;
                    $params['class_type'] = 1;
                    $params['qishu'] = $params['qishu']??1;
                    $params['community_id'] = $user['community_id'];
                    unset($params['delete_time']);
                    unset($params['update_time']);
                    if (isset($params['student_id'])) {
                        $params['student_id'] = join(",", $params['student_id']);
                    }
                    if (isset($params['manager_id'])) {
                        $params['manager_id'] = join(",", $params['manager_id']);
                    }


                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('添加成功','',['refresh'=>1]);
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        $this->assign("admin", $_SESSION['think']['admin']);
        /*$data=array("args"=>[[],[], []]);
        $leftOptions = $this->generateOptions('/user/user/lists',$data);
        $leftOptions = ($leftOptions==null)?[]:$leftOptions["leftOptions"];
        $rightOptions = $this->generateOptions('/user/user/lists');
        $rightOptions = ($rightOptions==null)?[]:$rightOptions["list"];
        $this->assignconfig("leftOptions", $leftOptions);
        $this->assignconfig("rightOptions", $rightOptions);*/
        $this->view->assign("classes_type", $classes_type);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {

        $classes_type = $this->request->request("classes_type");
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if($row['table_id']==null){
            $coursetableQuery = model("Coursetable")
                ->where("classes_id", "like", "%," . $row["id"] . ",%")
                ->whereOr("classes_id", "like", "%," . $row["id"])
                ->whereOr("classes_id", "like", $row["id"] . ",%")
                ->whereOr("classes_id", "=", $row["id"])
                ->find();
            if($coursetableQuery){
                $row['table_id']=$coursetableQuery["id"];
                $this->model->where("id", "=", $ids)->update(["table_id"=>$row['table_id']]);
            }
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    $validate = new \app\admin\validate\Classes();
                    if (!$validate->check($params)) {
                        //$this->error($validate->getError());
                    }
                    //名称查重
                    $where = [
                        'name' => $params['name'],
                        'id' => ['neq', $ids],
                        'status' => 1,
                    ];
                    if ($this->model->where($where)->find()) {
                        $this->error('名称重复');
                    }
                    //判断下拉菜单是否为空
                    if (isset($params['classes_type'])) {
                        if (empty($params['classes_type'])) {
                            $this->error('请选择班级类型');
                        }
                    }
                    if (isset($params['school_id'])) {
                        if (empty($params['school_id'])) {
                            $this->error('请选择学校');
                        }
                    }
                    if (isset($params['subject_lv'])) {
                        if (empty($params['subject_lv'])) {
                            $this->error('课程名称');
                        }
                    }
                    // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                    if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                        if (empty($row['city_id'])) {
                            $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                        }
                    }
                    if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                        if (empty($row['school_id'])) {
                            $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                        }
                    }

                    // 调试日志
                    error_log("Classes Edit - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                    $datatime = date("Y-m-d H:i:s");
                    $params['update_time'] = $datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    if (isset($params['leader_id']) && $params['leader_id'] != "") {
                        $params['leader_id'] = join(",", $params['leader_id']);
                    }
                    if (isset($params['manager_id']) && $params['manager_id'] != "") {
                        $params['manager_id'] = join(",", $params['manager_id']);
                    }
                    if (isset($params['image'])) {
                        $params['image'] = is_array($params['image']) ? json_encode($params['image'], JSON_UNESCAPED_UNICODE) : $params['image'];
                    }

                    //$params['manager_id']=join(",",$params['manager_id']);
                    //                    if($_SESSION['think']['admin']['group_id']==2){
                    //                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
                    //                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('修改成功','',['refresh'=>1]);
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($row["image"] != "") {
            $row["image"] = json_decode($row["image"]);
            if (is_string($row["image"])) {
                $row["image"] = json_decode($row["image"]);
            }
        } else {
            $row["image"] = [];
        }
        $row["image"] = json_encode($row["image"]);
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        $this->view->assign("row", $row);
        // 预先编码行数据为安全JSON字符串，供视图使用
        try {
            $rowJson = json_encode($row, JSON_UNESCAPED_UNICODE);
            // 使用ENT_QUOTES避免引号破坏HTML属性
            $rowJsonSafe = htmlspecialchars($rowJson ?: '{}', ENT_QUOTES);
        } catch (\Exception $e) {
            $rowJsonSafe = '{}';
        }
        $this->view->assign('row_json', $rowJsonSafe);
        /*        $teachers=($row["leader_id"]!="")?explode(",",$row["leader_id"]):[];
        $data=array("args"=>[$teachers,[], []]);
        $leftOptions = $this->generateOptions('/user/user/lists',$data);
        $leftOptions = ($leftOptions==null)?[]:$leftOptions["leftOptions"];
        $rightOptions = $this->generateOptions('/user/user/lists');
        $rightOptions = ($rightOptions==null)?[]:$rightOptions["list"];
        $this->assignconfig("leftOptions", $leftOptions);
        $this->assignconfig("rightOptions", $rightOptions);*/
        $this->view->assign("classes_type", $classes_type);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $where = "where 1=1";
        if ($_SESSION['think']['admin']['group_id'] != 1) {
            $where .= " and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page = 1;
        $pagesize = 50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " and $keyField='{$nn[$i]}'";
                    }
                }
            } else {
                $where = "where 1=1";
                if (isset($_REQUEST['city_id']) && $_REQUEST['city_id'] > 0) {
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
                if (isset($_REQUEST['table_id']) && $_REQUEST['table_id'] > 0) {
                    $where.=" and table_id=".$_REQUEST['table_id'];
                    $table=db::name("fa_course_table")->where("id","=",$_REQUEST['table_id'])->find();
                    $classes_ids=join(",",explode(",",$table['classes_id']));
                    $where.=" or id in (".$classes_ids.")";
                }
            }
        }
        $sql = "select id,name name from dev002_gxyusheng.classes $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        //        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
        //        if (empty($list)&&!empty($r_name)) {
        //            $data = array(
        //                "type" => "file",
        //                "pid" => 0,
        //                "name" => $r_name[0]['name']."学科",
        //                "title" => $r_name[0]['name'],
        //                "ismenu" => 0,
        //                "createtime" => time(),
        //                "updatetime" => time(),
        //                "status" => 1,
        //                "school_id" => $_REQUEST['school_id'],
        //            );
        //            $this->model->create($data);
        //        }
        //        $sql="select id,pid,name,title,status from dev002_gxyusheng.classes $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        //        $list = db()->query($sql);
        //        $tree = Tree::instance();
        //        $tree->init($list, 'pid');
        //        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.classes $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (\Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    /**
     * 修改状态（支持两种调用方式）
     */
    public function changestatus()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');

        if (empty($id)) {
            $this->error('参数错误');
        }

        try {
            // 查找记录
            $row = $this->model->where("id", "=", $id)->find();
            if (!$row) {
                echo json_encode(['code' => 0, 'msg' => '记录不存在']);
                return;
            }

            // 更新状态到eb_classes表（使用更直接的方式）
            $result = $this->model->where('id', $id)->update(['status' => $status]);
            if ($result !== false) {
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(['code' => 1, 'msg' => '状态更新成功']);exit;
            } else {
                echo json_encode(['code' => 0, 'msg' => '状态更新失败']);
            }
        } catch (\Exception $e) {
            echo json_encode(['code' => 0, 'msg' => '状态更新失败: ' . $e->getMessage()]);
        }
    }

    public function lists2($ids = NULL)
    {
        //$user=$this->auth->getUserInfo(true);
        $where = "where  classes_type=1 and status=1";
        if(isset($_REQUEST['table_id'])&&$_REQUEST['table_id']){
            $where.=" and table_id=".$_REQUEST['table_id'];
        }
        $page = 1;
        $pagesize = 50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " and $keyField='{$nn[$i]}'";
                    }
                }
            }
        }
        $sql = "select id,name name,classes_type from dev002_gxyusheng.eb_classes $where limit " . (($page - 1) * $pagesize) . ",$pagesize";

        $list = db()->query($sql);
        if ($_SESSION['think']['admin']['group_id'] == 3) {
            for ($i = 0; $i < count($list); $i++) {
                if ($list[$i]['classes_type'] != "1") {
                    unset($list[$i]);
                }
            }
        } elseif ($_SESSION['think']['admin']['group_id'] == 8) {
            for ($i = 0; $i < count($list); $i++) {
                if ($list[$i]['classes_type'] != "2") {
                    unset($list[$i]);
                }
            }
        }
        $total = db()->query("select count(1) as c from  dev002_gxyusheng.eb_classes $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    /**
     * AI自动生成图片 - 重定向到AI控制器
     */
    public function generateAiImage()
    {
        // 重定向到AI控制器处理
        $aiController = new \app\admin\controller\ai\Ai();
        return $aiController->generateImage();
    }

    public function classes_type()
    {
        $list = [
            ['id' => 1, 'name' => '学校班级'],
            ['id' => 2, 'name' => '社区班级'],
        ];
        echo json_encode(array("list" => $list));
        exit;
    }

    /**
     * 快捷搜索方法
     */
    public function quickSearch()
    {
        // 获取搜索参数
        $searchValue = $this->request->get('search', '');
        $searchType = (is_numeric($searchValue)) ? 'id' : 'text'; // id 或 text

        $relType = intval($this->request->get('rel_type', 1));
        $classStatus = $this->request->get('class_status', 0); // 0表示全部班级

        // 获取分页参数
        $page = intval($this->request->get('page', 1));
        $limit = intval($this->request->get('limit', 30));
        $offset = ($page - 1) * $limit;

        // 记录搜索日志
        file_put_contents(
            $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/quick_search.log",
            date('Y-m-d H:i:s') . " - 快捷搜索: 搜索值={$searchValue}, 类型={$searchType}, 班级类型={$relType}, 状态={$classStatus}\n",
            FILE_APPEND
        );

        try {
            if ($relType == 2) {
                // 社区班级搜索
                $result = $this->searchCommunityClasses($searchValue, $searchType, $classStatus, $offset, $limit);
            } else {
                // 学校班级搜索
                $result = $this->searchSchoolClasses($searchValue, $searchType, $classStatus, $offset, $limit);
            }

            // 返回与index方法相同的格式
            return json([
                'total' => $result['total'],
                'rows' => $result['rows']
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            file_put_contents(
                $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/quick_search.log",
                date('Y-m-d H:i:s') . " - 快捷搜索错误: " . $e->getMessage() . "\n",
                FILE_APPEND
            );

            // 返回与index方法相同的格式
            return json([
                'total' => 0,
                'rows' => []
            ]);
        }
    }

    /**
     * 搜索学校班级
     */
    private function searchSchoolClasses($searchValue, $searchType, $classStatus, $offset, $limit)
    {
        // 构建查询
        $query = $this->model->alias('c')
            ->join('eb_school school', 'school.id = c.school_id', 'LEFT')
            ->join('fa_cityarea city', 'city.id = c.city_id', 'LEFT')
            ->join('fa_course_table_autoplan_temp t', 't.classes_id = c.id', 'LEFT')
            ->join('fa_class_sequence s', 's.class_id = c.id', 'LEFT')
            ->where('c.status', '=', 1);

        // 权限控制
        if (isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
            $query->where('c.school_id', '=', $_SESSION['think']['admin']['school_id']);
        }

        // 班级类型过滤
        $query->where('c.classes_type', '=', 1); // 学校班级

        // 构建搜索条件
        if (!empty($searchValue)) {
            if ($searchType === 'id') {
                // ID精确搜索
                $query->where('c.id', '=', intval($searchValue));
            } else {
                // 多字段模糊搜索
                $query->where(function ($q) use ($searchValue) {
                    $q->where('c.name', 'like', "%{$searchValue}%")
                        ->whereOr('school.name', 'like', "%{$searchValue}%")
                        ->whereOr('city.name', 'like', "%{$searchValue}%");
                });
            }
        }

        // 状态筛选（如果不是全部班级）
        if ($classStatus != 0) {
            $today = date('Y-m-d');
            if ($classStatus == 1) {
                // 正在进行中
                $query->group('c.id')->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '{$today}')");
            } elseif ($classStatus == 2) {
                // 已结束
                $query->group('c.id')->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '{$today}')");
            } elseif ($classStatus == 'unscheduled') {
                // 未排课
                $query->group('c.id')->having("MAX(t.date) IS NULL");
            }
        } else {
            // 全部班级，仍需要分组获取日期信息
            $query->group('c.id');
        }

        // 获取总数
        $totalQuery = clone $query;
        $total = $totalQuery->count();

        // 获取列表数据
        $list = $query->field('c.*, t.date as start_date, t.date as end_date, 
                              t.ocation_id, t.id as t_id, s.sequence_number, s.class_type as sequence_type,
                              school.name as school_name, city.name as city_name')
            ->order('s.sequence_number', 'asc')
            ->limit($offset, $limit)
            ->select();

        // 处理数据格式
        $listArray = is_array($list) ? $list : $list->toArray();
        $list = $this->formatSchoolClassData($listArray);

        return ['rows' => $list, 'total' => $total];
    }

    /**
     * 搜索社区班级
     */
    private function searchCommunityClasses($searchValue, $searchType, $classStatus, $offset, $limit)
    {
        // 构建查询
        $query = Db::name('ocation_class')->alias('oc')
            ->join('fa_community community', 'community.id = oc.community_id', 'LEFT')
            ->join('fa_ocation ocation', 'ocation.id = oc.ocation_id', 'LEFT')
            ->join('fa_course_table_autoplan_temp t', 't.ocation_class_id = oc.id', 'LEFT')
            ->where('oc.status', '=', 1);

        // 权限控制
        if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8) {
            // 社区管理员权限控制
            $allowedOcationIds = model("Ocation")::getChildOcationIds($_SESSION['think']['admin']['ocation_id'], true);
            if (!empty($allowedOcationIds)) {
                $query->where('oc.ocation_id', 'in', $allowedOcationIds);
            } else {
                // 没有权限，返回空结果
                return ['rows' => [], 'total' => 0];
            }
        }

        // 构建搜索条件
        if (!empty($searchValue)) {
            if ($searchType === 'id') {
                // ID精确搜索
                $query->where('oc.id', '=', intval($searchValue));
            } else {
                // 多字段模糊搜索
                $query->where(function ($q) use ($searchValue) {
                    $q->where('oc.name', 'like', "%{$searchValue}%")
                        ->whereOr('community.name', 'like', "%{$searchValue}%")
                        ->whereOr('ocation.name', 'like', "%{$searchValue}%");
                });
            }
        }

        // ================== 关键修改：使用派生表JOIN确保每个ocation_id只取最小的oc.id ==================
        // 构建派生表SQL：按ocation_id取状态为1的最小id
        $minIdSubSql = Db::name('ocation_class')->alias('oc2')
            ->where('oc2.status', 1)
            ->field('MIN(oc2.id) AS min_id, oc2.ocation_id')
            ->group('oc2.ocation_id')
            ->buildSql();

        // 与派生表进行内连接，确保只保留每个ocation_id的最小oc.id记录
        $query->join([$minIdSubSql => 'oc_min'], 'oc_min.ocation_id = oc.ocation_id AND oc.id = oc_min.min_id', 'INNER');
        // ===================================================================================

        // 状态筛选（如果不是全部班级）
        if ($classStatus != 0) {
            $today = date('Y-m-d');
            if ($classStatus == 1) {
                // 正在进行中
                $query->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) >= '{$today}')");
            } elseif ($classStatus == 2) {
                // 已结束
                $query->having("(MAX(t.date) IS NOT NULL AND DATE(MAX(t.date)) < '{$today}')");
            } elseif ($classStatus == 'unscheduled') {
                // 未排课
                $query->having("MAX(t.date) IS NULL");
            }
            $query->group('oc.ocation_id');  // 状态筛选按group_id分组以每组仅保留最小oc.id
        } else {
            // 全部班级，仍需要分组获取日期信息
            $query->group('oc.ocation_id');
        }

        // 获取总数（使用修改后的查询逻辑）
        $totalQuery = clone $query;
        $total = $totalQuery->count();

        // 获取列表数据
        $list = $query->field('oc.id, oc.community_id, oc.ocation_id, oc.cover, oc.name, 
                          oc.id as class_id, t.city_id, t.school_id, 
                          MIN(t.date) as start_date, MAX(t.date) as end_date, 
                          t.ocation_id, t.id as t_id, oc.id as sequence_number, 
                          "ocation_class" as sequence_type, 2 as classes_type,
                          community.name as community_name, ocation.name as ocation_name')
            ->order('oc.id', 'asc')
            ->group('oc.ocation_id')  // 按group_id分组（由于已JOIN最小id子查询，每组只保留最小oc.id记录）
            ->limit($offset, $limit)
            ->select();

        // 处理数据格式
        $listArray = is_array($list) ? $list : $list->toArray();
        $list = $this->formatCommunityClassData($listArray);

        return ['rows' => $list, 'total' => $total];
    }

    /**
     * 格式化学校班级数据
     */
    private function formatSchoolClassData($list)
    {
        foreach ($list as &$item) {
            // 处理各种字段的文本显示
            $item['city_id'] = model("Cityarea")->getCity_idTextAttr($item['city_id'], $item);
            $item['school_id'] = model("School")->getSchool_idTextAttr($item['school_id'], $item);
            $item['subject_lv'] = model("Subjectlv")->getSubject_lvTextAttr($item['subject_lv'], $item);
            $item['rel_id'] = model("School")->getSchool_idTextAttr($item['rel_id'], $item);
            $item['community_id'] = model("Community")->getCommunity_idTextAttr($item['community_id'], $item);
            $item['ocation_id'] = model("Ocation")->getOcation_idTextAttr($item['ocation_id'], $item);

            // 处理班级序号
            if (!empty($item['sequence_number'])) {
                $prefix = $item['sequence_type'] == 1 ? 'S-' : 'C-';
                $item['formatted_sequence'] = $prefix . str_pad($item['sequence_number'], 3, '0', STR_PAD_LEFT);
            } else {
                $item['formatted_sequence'] = '';
            }

            // 处理封面图片
            $item['cover'] = createImg($_SERVER["DOCUMENT_ROOT"] . "/" . $item["cover"], "220", "220");

            // 获取报名人数
            $item['apply_num'] = Db::name("eb_apply_form_item")
                ->where("classes_id", $item['id'])
                ->where("status", 1)
                ->count();
        }

        return $list;
    }

    /**
     * 格式化社区班级数据
     */
    private function formatCommunityClassData($list)
    {
        foreach ($list as &$item) {
            // 处理社区和教学点字段
            $item['community_id'] = model("Community")->getCommunity_idTextAttr($item['community_id'], $item);
            $item['ocation_id'] = model("Ocation")->getOcation_idTextAttr($item['ocation_id'], $item);

            // 处理班级序号
            if (!empty($item['sequence_number'])) {
                $prefix = 'C-'; // 社区班级统一使用C-前缀
                $item['formatted_sequence'] = $prefix . str_pad($item['sequence_number'], 3, '0', STR_PAD_LEFT);
            } else {
                $item['formatted_sequence'] = '';
            }

            // 处理封面图片
            $item['cover'] = createImg($_SERVER["DOCUMENT_ROOT"] . "/" . $item["cover"], "220", "220");
        }

        return $list;
    }

    /**
     * 重写selectpage方法，避免$query变量未定义的问题
     */
    protected function selectpage()
    {
        // 初始化可能缺失的变量
        $query = null;

        try {
            return parent::selectpage();
        } catch (\Exception $e) {
            // 记录错误日志
            file_put_contents(
                $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/sql_debug.log",
                date('Y-m-d H:i:s') . " - Selectpage错误: " . $e->getMessage() . "\n",
                FILE_APPEND
            );

            // 返回空结果
            return json(['list' => [], 'total' => 0]);
        }
    }
}
